#include "iot_switch_mainwindow.h"
#include "ui_iot_switch_mainwindow.h"

iot_switch_mainWindow::iot_switch_mainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::iot_switch_mainWindow)
{
    ui->setupUi(this);
    setWindowFlags(windowFlags() & ~Qt::WindowMaximizeButtonHint);  //取消最大化
    setFixedSize(this->width(), this->height());                    //禁止调整大小

    //创建系统托盘任务
    m_systemTray = new QSystemTrayIcon(this);
    m_systemTray->setIcon(QIcon(":/Uimg1.ico"));
    m_systemTray->setToolTip("物联网开关控制终端");
    connect(m_systemTray, &QSystemTrayIcon::activated, this, &iot_switch_mainWindow::activatedSystemTrayIcon);
    m_systemTray->show();

    isHide = false;
    qMenuBug = true;
    m_menu = new QMenu(this);
    m_action1 = new QAction(m_menu);
    m_action2 = new QAction(m_menu);
    m_action1->setText("Hide Window");
    m_action2->setText("Close Window");
    m_menu->addAction(m_action1);
    m_menu->addAction(m_action2);
    connect(m_action1, &QAction::triggered, this, &iot_switch_mainWindow::showWindows);
    connect(m_action2, &QAction::triggered, this, &iot_switch_mainWindow::closeWindows);


    //init pubCount
    pubCount = 0;

    //init switchStatus
    for(int i = 0; i < 4; i++)
    {
        switchStatus[i] = 0;
    }

    //init ui button to array
    pBtnArray[0] = ui->ch1Btn;
    pBtnArray[1] = ui->ch2Btn;
    pBtnArray[2] = ui->ch3Btn;
    pBtnArray[3] = ui->ch4Btn;

    for(int i = 0; i < 4; i++)//将4个开关的点击事件绑定到clickSwitch函数
    {
        connect(pBtnArray[i], &QPushButton::clicked, this, &iot_switch_mainWindow::clickSwitch);
    }

    client = new QMQTT::Client(QHostAddress("47.92.129.18"), 1883);
    client->setClientId("qwerwasdfzxcvqwerasdfzxcv");//设置连接的id，最好乱序，不然容易和别人的同名
    client->connectToHost();

    connect(client, &QMQTT::Client::error, this, &iot_switch_mainWindow::connectError);
    connect(client, &QMQTT::Client::connected, this, &iot_switch_mainWindow::connected);
    connect(client, &QMQTT::Client::disconnected, this, &iot_switch_mainWindow::disconnected);
    connect(client, &QMQTT::Client::published, this,&iot_switch_mainWindow::published);

    this->grabKeyboard();//监听键盘事件
}

iot_switch_mainWindow::~iot_switch_mainWindow()
{
    delete ui;
}

void iot_switch_mainWindow::clickSwitch()
{
    QObject *object = sender();
    QPushButton *button = dynamic_cast<QPushButton*>(object);//基类转派生类
    if(button->text().lastIndexOf("off") != -1) // 找到就是关的
    {
        button->setText(button->text().replace("off", "on"));
    }
    else
    {
        button->setText(button->text().replace("on", "off"));
    }

    //变化后获取按钮的off-on
    for(int i = 0; i < 4; i++)
    {
        switchStatus[i] = getSwitchStatus(pBtnArray[i]);
    }
    publishMsg();
}

void iot_switch_mainWindow::connectError(const QMQTT::ClientError error)
{
    QString errMeg = QString("error code : %1").arg(error, 2, 10);
    QMessageBox::critical(this, "MQTT错误", errMeg, QMessageBox::Ok);
}

void iot_switch_mainWindow::connected()
{
    ui->connectStatusLb->setText("MQTT状态：已连接");
}

void iot_switch_mainWindow::disconnected()
{
    ui->connectStatusLb->setText("MQTT状态：断开连接");
}

void iot_switch_mainWindow::published(const QMQTT::Message& message, quint16)
{
    QString msg_payload = QString(message.payload());
    QString msg = QString("msgid:%1 payload:%2").arg(pubCount++, 5, 10).arg(msg_payload);
    ui->pubTextBrowser->append(msg);
}

void iot_switch_mainWindow::showWindows()
{
    if(isHide)
    {
        m_action1->setText("Hide Window");
        isHide = false;
        this->show();
    }
    else
    {
        m_action1->setText("Show Window");
        isHide = true;
        this->hide();
    }
}

void iot_switch_mainWindow::closeWindows()
{
    this->close();
}


void iot_switch_mainWindow::activatedSystemTrayIcon(QSystemTrayIcon::ActivationReason)
{
    int menu_height = m_menu->height();
    QPoint pt = QCursor::pos();
    pt.setY(pt.y() - (qMenuBug?menu_height+20:menu_height));
    qMenuBug = false;
    m_menu->exec(pt);
}

int iot_switch_mainWindow::getSwitchStatus(QPushButton *button)
{
    if(button->text().lastIndexOf("off") != -1)
    {
        return 0;
    }
    else
    {
        return 1;
    }
}

// 键盘按下
void iot_switch_mainWindow::keyPressEvent(QKeyEvent *event)
{
//    qDebug() << "keyPressEvent=" << event->key();
    if(event->key() == Qt::Key_Enter)//回车占位
    {
        return;
    }
}

// 键盘松开
void iot_switch_mainWindow::keyReleaseEvent(QKeyEvent *event)
{
//    qDebug() << "keyReleaseEvent=" << event->key();

    switch (event->key()) {
    case Qt::Key_1:
        switchStatus[0] = switchStatus[0]==0?1:0;
        pBtnArray[0]->setText(switchStatus[0]==0?"CH1:off":"CH1:on");
        break;
    case Qt::Key_2:
        switchStatus[1] = switchStatus[1]==0?1:0;
        pBtnArray[1]->setText(switchStatus[1]==0?"CH2:off":"CH2:on");
        break;
    case Qt::Key_3:
        switchStatus[2] = switchStatus[2]==0?1:0;
        pBtnArray[2]->setText(switchStatus[2]==0?"CH3:off":"CH3:on");
        break;
    case Qt::Key_4:
        switchStatus[3] = switchStatus[3]==0?1:0;
        pBtnArray[3]->setText(switchStatus[3]==0?"CH4:off":"CH4:on");
        break;
    default:
        break;
    }
    publishMsg();
}

void iot_switch_mainWindow::publishMsg()
{
    QString mqttPubDataString = QString("{\"cmdlist\":[%1,%2,%3,%4]}")
            .arg(switchStatus[0], 1, 10)
            .arg(switchStatus[1], 1, 10)
            .arg(switchStatus[2], 1, 10)
            .arg(switchStatus[3], 1, 10);
//    qDebug() << mqttPubDataString << endl;
    // 发送MQTT信息
    QMQTT::Message msg = QMQTT::Message();
    msg.setQos(0);
    msg.setTopic("SmartHome-Pub-SetRelay");
    msg.setPayload(mqttPubDataString.toUtf8());
    this->client->publish(msg);
}

